package com.ruoyi.procured.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.ProcuredOrders;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.procured.domain.PaymentRequest;
import com.ruoyi.procured.domain.PaymentRequestLog;
import com.ruoyi.procured.domain.PaymentReturn;
import com.ruoyi.procured.domain.vo.PaymentRequestLogVo;
import com.ruoyi.procured.domain.vo.PaymentReturnFormUpload;
import com.ruoyi.procured.domain.vo.PaymentReturnVO;
import com.ruoyi.procured.mapper.PaymentRequestLogMapper;
import com.ruoyi.procured.mapper.PaymentRequestMapper;
import com.ruoyi.procured.mapper.PaymentReturnMapper;
import com.ruoyi.procured.mapper.ProcuredOrdersMapper;
import com.ruoyi.procured.service.IPaymentReturnService;
import com.ruoyi.procured.service.PaymentRequestLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class PaymentReturnServiceImpl extends ServiceImpl<PaymentReturnMapper, PaymentReturn>
    implements IPaymentReturnService {

    @Autowired
    private PaymentReturnMapper paymentReturnMapper;
    @Autowired
    private PaymentRequestMapper paymentRequestMapper;
    @Autowired
    private PaymentRequestProcessServiceImpl paymentRequestProcessService;
    @Autowired
    private ProcuredOrdersMapper procuredOrdersMapper;
    /**
     * 查询退款单列表
     */
    @Override
    public List<PaymentReturnVO> selectPaymentReturnVoList(PaymentReturnVO paymentReturnVO) {
        List<PaymentReturnVO> mainList = paymentReturnMapper.selectPaymentReturnVoList(paymentReturnVO);
        if (!mainList.isEmpty()) {
            // 提取主表ID
            List<String> paymentRequestIds = mainList.stream()
                    .map(PaymentReturnVO::getPaymentRequestId)
                    .collect(Collectors.toList());

            // 第二步：查询关联的items
            List<PaymentReturn> items = paymentReturnMapper.selectPaymentReturnItems(paymentRequestIds);

            // 按paymentRequestId分组
            Map<String, List<PaymentReturn>> itemsMap = items.stream()
                    .collect(Collectors.groupingBy(PaymentReturn::getPaymentRequestId));

            // 组装数据
            mainList.forEach(vo -> {
                vo.setItems(itemsMap.getOrDefault(vo.getPaymentRequestId(), new ArrayList<>()));
            });
        }
        return mainList;
    }
    /**
     * 上传退款单
     */
    @Override
    @Transactional
    public int uploadReturnImage(PaymentReturnFormUpload formUpload, String nickname) {
        String paymentRequestId = formUpload.getPaymentRequestId();
        String returnImage = formUpload.getReturnImage();
        String procuredOrderId = formUpload.getProcuredOrderId();

        //更新退款单路径,付款单状态
        LambdaUpdateWrapper<PaymentRequest> qw = new LambdaUpdateWrapper<>();
        qw.eq(PaymentRequest::getPaymentRequestId,paymentRequestId);
        qw.set(PaymentRequest::getReturnImage, returnImage);
        qw.set(PaymentRequest::getUpdateBy,nickname);
        qw.set(PaymentRequest::getUpdateTime, DateUtils.getNowDate());
        paymentRequestMapper.update(null,qw);

        //更新日志
        paymentRequestProcessService.savePaymentRequestLog(paymentRequestId,"1",nickname,"上传收款单");

        //更新采购订单表的：申请退款状态（0未申请退款，1部分申请退款，2已全部申请退款，3部分退款，4已全部退款）
        ProcuredOrders p = new ProcuredOrders();
        p.setOrdersId(Long.valueOf(procuredOrderId));
        if(paymentReturnMapper.isFullyPaidToReturn(procuredOrderId)){
            //采购订单付款状态（申请退款状态（0未申请退款，1部分申请退款，2已全部申请退款，3部分退款，4已全部退款）
            p.setReturnStatus("4");
        }else{
            p.setReturnStatus("3");
        }
        return procuredOrdersMapper.updateProcuredOrders(p);
    }

    /**
     * 标记退款单已收款
     */
    @Override
    @Transactional
    public int setPaymentRequestMark(String paymentRequestId, String nickname) {
        PaymentRequest paymentRequest = paymentRequestMapper.selectById(paymentRequestId);
        if(paymentRequest == null){
            throw new ServiceException("获取退款单信息失败");
        }
        if(paymentRequest.getReturnStatus().equals("1")){
            throw new ServiceException("退款单已标记，请勿重复标记");
        }
        paymentRequest.setReturnStatus("1");
        paymentRequestMapper.updateById(paymentRequest);
        //更新日志
        paymentRequestProcessService.savePaymentRequestLog(paymentRequestId,"1",nickname,"标记已收款");


        return 0;
    }
}




